package com.baide.sanguanheyi.plc;

import com.baide.sanguanheyi.config.ThreadManager;
import com.baide.sanguanheyi.interfaces.PlcCallBack;
import com.baide.sanguanheyi.luodao.LService;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: create by DFX
 * @Date: 2020/4/23 22:20
 * @Version: V1.0.0
 * @Tips:
 */
@Component
public class NioObjectHandle {

    private Logger logger = LoggerFactory.getLogger(NioObjectHandle.class);

    @Autowired
    private PlcConfig plcConfig;
    @Autowired
    private NioServer nioServer;
    @Autowired
    private LService service;
    PlcCallBack callBack;

    public void setCallBack(PlcCallBack callBack) {
        this.callBack = callBack;
    }

    public static StringBuffer recieveBuffer = new StringBuffer();

    /**
     * @author create by DFX
     * @Version: V1.0.0
     * @Tips Netty 通信程序,处理不同客户端发送的数据
     */
    public void receiver(Channel channel, String in) {
        // TCP沾包处理
//        recieveBuffer += in;
//        recieveBuffer = recieveBuffer.replace("*", "#");
//        int last = recieveBuffer.lastIndexOf("#");
//        if (last > 0) {
//            handleRecieveInfo(recieveBuffer.substring(0, last + 1), channel);
//            recieveBuffer = recieveBuffer.substring(last + 1);

//        }
        synchronized (this) {
            if (recieveBuffer.toString().startsWith(" ")) {
                String ss = recieveBuffer.toString().trim().replaceAll(" ", "");
                recieveBuffer.delete(0, recieveBuffer.length());
                recieveBuffer.append(ss);
            }
            String s = in.trim().replaceAll(" ", "");
            recieveBuffer.append(s);
            while (recieveBuffer.toString().startsWith("*") && recieveBuffer.toString().contains("#") && recieveBuffer.length() > 2) {
                handleRecieveInfo(recieveBuffer.substring(1, recieveBuffer.indexOf("#")), channel);
                recieveBuffer.delete(0, recieveBuffer.indexOf("#") + 1);
            }
        }
    }

    /**
     * @author create by DFX
     * @Version: V1.0.0
     * @Tips 处理不同客户端发送数据，并进行与主线程的回调传值
     */
    public void handleRecieveInfo(String msg, Channel channel) {
        ThreadManager.getThreadPollProxy().execute(new Runnable() {
            @Override
            public void run() {
                String ipAddress = channel.remoteAddress().toString().substring(1, channel.remoteAddress().toString().indexOf(":"));
                if (ipAddress.equals(plcConfig.getObr1())) {  // OBR1
                    callBack.OBR(1, msg);
                } else if (ipAddress.equals(plcConfig.getObr2())) { // OBR2
                    callBack.OBR(2, msg);
                } else if (ipAddress.equals(plcConfig.getObr3())) { // OBR3
                    callBack.OBR(3, msg);
                } else if (ipAddress.equals(plcConfig.getPlc())) { // PLC
                    logger.info("收到PLC信息：" + msg);
                    if (msg.equals("999")) {
                        callBack.light(999);
                    } else if (msg.equals("998")) {
                        callBack.light(998);
                    } else {
                        String code = msg.substring(0, 1);
                        // 功能码判断
                        if ("D".equals(code)) { // 光电反馈指令
                            callBack.light(Integer.valueOf(msg.substring(1, 2)));
                        }
                    }
                }
            }
        });

    }


    /**
     * @author create by DFX
     * @Version: V1.0.0
     * @Tips Netty 通信程序主动发送
     */
    public void senderComandInfo(String ipAddress, String messageInfo) {
        ThreadManager.getThreadPollProxy().execute(new Runnable() {
            @Override
            public void run() {
                logger.info("发送指令给PLC:" + messageInfo);
                Channel channel = NioChannelMap.get(ipAddress);
                if (channel.isActive()) {
                    channel.writeAndFlush(messageInfo);
                }
            }
        });
    }

    /**
     * @author crete by DFX
     * @version v1.0.0
     * @Tips 处理接收移栽命令
     */
    public void move(int plcNo, int position) { // *A21#
        senderComandInfo(plcConfig.getPlc(), "*A" + plcNo + position + "#");
    }

    /**
     * @author crete by DFX
     * @version v1.0.0
     * @Tips 处理接受上包站皮带停止命令
     */
    public void start2Stop(int stop) { // *B1#
        senderComandInfo(plcConfig.getPlc(), "*B" + stop + "#");
    }

    /**
     * @author crete by DFX
     * @version v1.0.0
     * @Tips 处理接受线体启停命令
     */
    public void line2Stop(int stop) { // *C1#
        senderComandInfo(plcConfig.getPlc(), "*C" + stop + "#");
    }

    /**
     * @param stop 1是停，0是恢复
     */
    public void line2night(int stop) {//*E1#
        senderComandInfo(plcConfig.getPlc(), "*E" + stop + "#");
    }

    public void stopAll() {
        senderComandInfo(plcConfig.getPlc(), "*F1#");
    }

    public void sendMsg(String msg) {
        senderComandInfo(plcConfig.getPlc(), msg);
    }
}
